/**
 * 实现treePath方法：二叉树的所有路径
 */

type Tree = {
  value: number;
  left?: Tree;
  right?: Tree;
};

const tree: Tree = {
  value: 1,
  left: {
    value: 2,
    right: { value: 5 }
  },
  right: { value: 3 }
};

function treePath(root: Tree): string[] {
  const result: string[] = [];
  dfs(root, result, "");
  return result;
}

function dfs(node: Tree | undefined, paths: string[], path: string) {
  if (!node) return;
  if (!node.left && !node.right) {
    // 遇到叶子节点则返回路径
    paths.push(path + node.value.toString());
    return;
  }
  path += node.value + "->";
  dfs(node.left, paths, path);
  dfs(node.right, paths, path);
}

// 测试
console.log(treePath(tree)); // ['1->2->5', '1->3']
